'use strict';
const moment = require('moment');
const CryptoJS = require('crypto-js');

const hash = (function () {
  const hashMap = [];
  function beforeHash() {
    const lowerCase = [];
    const upperCase = [];
    for (let i = 97; i < 123; i++) {
      lowerCase.push(String.fromCharCode(i));
    }
    for (let i = 65; i < 91; i++) {
      upperCase.push(String.fromCharCode(i));
    }
    const strs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].concat(
      lowerCase,
      upperCase,
      new Date().getTime().toString().split('')
    );
    // eslint-disable-next-line no-unused-vars
    function calculte(len) {
      return new Array(len)
        .fill()
        .map(() => strs[Math.floor(Math.random() * 63)])
        .join('');
    }

    return function (len) {
      let res = calculte(len);
      while (hashMap.includes(res)) {
        res = calculte(len);
      }
      hashMap.push(res);
      return res;
    };
  }
  return beforeHash();
})();
module.exports = {
  hash,
  now() {
    return moment().format('YYYY-MM-DD HH:mm:ss.SSS');
  },
  encode(data) {
    console.log(this.app.config.encodeKey, this.app.config.encodeIv);
    const ciphertext = CryptoJS.AES.encrypt(
      data,
      CryptoJS.enc.Utf8.parse(this.app.config.encodeKey),
      {
        iv: CryptoJS.enc.Utf8.parse(this.app.config.encodeIv),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
      }
    );
    return ciphertext.toString();
  },
};
